<template>
    <UxDialog :visible="visible" @close="visible = false">
        <div class="embroidery-editor">
            <EmbroideryPreview :stitches="stitches" :colors="colorFormat" />
            <div class="embroidery-options" v-if=value>
                <h2>File information</h2>
                <UxTemplateInputInline v-model="name" />
                <p>Size: {{ [value.width / 10, value.height / 10].join('*') }} mm</p>
                <p>Needle: {{ value.stitches_count }}</p>
                <h2>Thread colors </h2>
                <EmbroideryEditorColor v-model="colors" />

                <button type="primary" @click="doSubmit()">Save</button>
            </div>

            <UxLoading2 :loading="loading" />

        </div>
    </UxDialog>

</template>
<script>
import Md5 from "js-md5";
import { getStitchesByBase64 } from "@/utils/EmbroideryDst.js";
import { writeCanvas } from "@/utils/EmbroideryCanvas.js";
import { colors, Pattern } from "@/utils/EmbroideryPattern.js";
import { mapGetters } from "vuex";

export default {
    props: {
        value: { type: Object, default: () => null },
    },
    data () {
        return {
            loading: false,
            name: '',
            colors: [],
            stitches: [],
        };
    },
    computed: {
        ...mapGetters("user", {
            userInfo: "getUserInfo",
        }),
        visible: {
            get () { return !!this.value },
            set (val) {
                !val && this.$emit('input', null)
            },
        },
        colorFormat () {
            return this.colors.map(i => colors.find(c => c.code == i)).filter(i => i)
        }
    },
    watch: {
        visible () {
            if (this.value) {
                this.loading = true;
                const stitches = getStitchesByBase64(this.value.stitches)
                this.colors = this.value.line_color.split(',').filter(i => i)
                this.stitches = stitches;
                this.name = this.value.file_name;
                this.loading = false;
            }
        }
    },
    methods: {

        getThumb () {

            const color = this.colors.join(',')

            if (color == this.value.line_color) {
                Promise.resolve(this.value.img_url)
            } else {

                const canvas = writeCanvas(this.stitches, this.colorFormat)
                const email = (this.userInfo || {}).email;
                const folder = email ? Md5(email) : 'noemail';
                const path = ('data/pod/file/' + folder).replace(/\/+$/, '') + '/';

                const time = new Date().getTime();
                const random = Math.random().toFixed(10).substring(2);

                return new Promise((resolve, reject) => {
                    canvas.toBlob(blob => {
                        const request = {
                            file: blob,
                            name: time + "-" + random + ".png",
                            path: path,
                        };
                        this.$uploadToOSS(request, response => {
                            if (response.code === 0 && response.data) {
                                resolve(response.data || '');
                            } else {
                                reject(response.msg || "Please check your network connection and try again.");
                            }
                        })

                    }, "image/png", 1)
                })
            }
        },

        // 保存
        doSubmit () {

            this.loading = true
            this.getThumb().then(url => {
                const request = {
                    img_url: url,
                    line_color: this.colors.join(','),
                    file_name: this.name,
                }
                return this.$http("Material.setEmbDetail/" + this.value.id, request);
            }).then(res => {
                if (res.code === 0) {
                    this.$uxMessage.success('Embroidery file updated successfully!');
                    this.$emit('reload')
                    this.$emit('input', null)
                    this.loading = false;
                } else {
                    return Promise.reject(res.msg)
                }
            }).catch(err => {
                this.$uxMessage.error(err);
                this.loading = false;
            })
        }
    },
};
</script>

<style lang="scss" scoped>
.embroidery-editor {
    width: 80vw;
    height: 80vh;
    max-width: 1140px;
    max-height: 840px;
    display: flex;
    position: relative;
}

.embroidery-view {
    flex: 1;
    position: relative;
    overflow: hidden;

    &::before {
        content: '';
        display: block;
        padding-bottom: 100%;
    }

    .embroidery-preview {
        position: absolute;
        left: 0;
        top: 0;
        width: 100%;
        height: 100%;
    }
}

.embroidery-options {
    width: 400px;
    padding: 20px;
    border: 1px solid #ddd;
    height: 100%;
    box-sizing: border-box;
}
</style>
